/* $RCSFile: TypeConverterNameValue.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Country/TypeConverterNameValue.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.ComponentModel;
using System.Collections.Specialized;

namespace AddonNice.Country
{

	/// <summary>
	/// TypeConverterNameValue converter can convert From/To 
	/// NameValueCollection and string values
	/// </summary>
	public class TypeConverterNameValue : TypeConverter
	{
		// Overrides the CanConvertFrom method of TypeConverter.
		// The ITypeDescriptorContext interface provides the context for the
		// conversion. Typically this interface is used at design time to 
		// provide information about the design-time container.
		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 
		{
			if (sourceType == typeof(string)) 
			{
				return true;
			}
			if (sourceType == typeof(NameValueCollection)) 
			{
				return true;
			}
			return base.CanConvertFrom(context, sourceType);
		}

		public NameValueCollection ConvertFromString(string value, char[] itemsSeparator, char[] keyValueSeparator)
		{
			if (value == null)
				return null;

			//Check separator: cannot be equal
			if (itemsSeparator.Equals(keyValueSeparator))
				throw new ArgumentException("keyValueSeparator and itemsSeparator cannot have the same value", "keyValueSeparator");

			//Check separator: cannot be equal -HACK for net bug
			if (itemsSeparator.Length == 1 && keyValueSeparator.Length == 1 && itemsSeparator[0] == keyValueSeparator[0])
				throw new ArgumentException("keyValueSeparator and itemsSeparator cannot have the same value", "keyValueSeparator");

			//Trim last separator if found
			value = value.TrimEnd(itemsSeparator);

			string[] nameValues = value.Split(itemsSeparator);
			NameValueCollection nameValueColl = new NameValueCollection();

			foreach (string nameValue in nameValues)
			{
				if (nameValue != string.Empty)
				{
					string[] arrNameValue = nameValue.Split(keyValueSeparator);
				
					if (arrNameValue.Length == 2)
					{
						nameValueColl.Add(arrNameValue[0], arrNameValue[1]);
					}
					if (arrNameValue.Length == 1)
					{
						nameValueColl.Add(arrNameValue[0], string.Empty);
					}
				}
			}
		
			return nameValueColl;
		}

		public new NameValueCollection ConvertFromString(string value)
		{
			return ConvertFromString(value, new Char[] {';'}, new Char[] {'='});
		}

	}
}
